<?php
/*
 * @Description:高危许可证管理
 * @FilePath: \auxface_certificate\app\certificate\controller\user\v1\Risk.php
 */

declare(strict_types=1);

namespace app\certificate\controller\user\v1;

use Exception;
use think\facade\Db;
use think\Request;

class Risk
{
    /**
     * @Description: 获取许可证类型列表
     * @param {Request} $request
     */
    public function getTypeList(Request $request)
    {
        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['rt.formUuid', '<>', ''],
            ['aw.wxappUserUuid', '=', $request->uuid],
            ['rt.isDelete', '=', 0],
            ['aw.isDelete', '=', 0],
            ['ta.isDelete', '=', 0],
        ];

        $list = DB::table('certificate_riskType')
            ->alias('rt')
            ->join('certificate_areaType at', 'at.typeUuid = rt.uuid')
            ->join('certificate_areaWorker aw', 'aw.areaUuid = at.areaUuid')
            ->join('certificate_riskTypeAuth ta', 'ta.typeUuid = rt.uuid')
            ->order(['rt.id desc'])
            ->where($searchWhere)
            ->field(['rt.name', 'rt.uuid', 'rt.subtitle'])
            ->distinct(true)
            ->select()->toArray();

        return result(SUCCESS, $list, '');
    }

    /**
     * 许可证类型类型
     *
     * @param Request $request
     * @return void
     */
    public function getTypeDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['rt.formUuid', '<>', ''],
            ['aw.wxappUserUuid', '=', $request->uuid],
            ['rt.isDelete', '=', 0],
            ['aw.isDelete', '=', 0],
            ['ta.isDelete', '=', 0],
        ];

        $auth = DB::table('certificate_riskType')
            ->alias('rt')
            ->join('certificate_areaType at', 'at.typeUuid = rt.uuid')
            ->join('certificate_areaWorker aw', 'aw.areaUuid = at.areaUuid')
            ->join('certificate_riskTypeAuth ta', 'ta.typeUuid = rt.uuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有权限查看');

        $where = [
            'rt.isDelete' => 0,
            'rt.uuid' => $uuid
        ];
        //查看有没有提交过的记录
        $riskData = DB::table('certificate_riskType')
            ->alias('rt')
            ->join('certificate_formtemplate f', 'f.uuid=rt.formUuid', 'left')
            ->where($where)
            ->field(['f.fields as formData', 'rt.name', 'rt.uuid'])
            ->findOrEmpty();
        if (!$riskData) return result(FAIL, '', '獲取失敗，請返回重試');
        $riskData['formData'] = json_decode(html_entity_decode($riskData['formData'] ?? ''), true) ?: [];
        foreach ($riskData['formData'] as $key => $value) {
            if ($value['tag'] == 'signature') {
                unset($riskData['formData'][$key]);
            }
        }
        return result(SUCCESS, $riskData, '');
    }

    /**
     * @Description: 获取申请列表
     * @param {Request} $request
     */
    public function getApplyList(Request $request)
    {
        $data  = $request->data;
        $limit =  $data['limit'];
        $page =  $data['page'];

        $searchWhere = [
            ['r.isDelete', '=', '0']
        ];

        // 获取当前用户具有审核权限的类型Uuid
        $auditedTypeUuids = DB::table('certificate_riskTypeAuth')
            ->alias('a')
            ->join('certificate_areaWorker w', 'w.wxappUserUuid = a.wxappUserUuid')
            ->where('a.wxappUserUuid', $request->uuid)
            ->where('a.isAudit', 1)  // 假设 isAudit 字段表示是否具有审核权限
            ->where('w.isDelete', 0)
            ->where('a.isDelete', 0)
            ->column('a.typeUuid') ?: [];
        // 组合条件：筛选用户自己申请的记录或者用户具有审核权限的记录
        array_push($searchWhere, function ($query) use ($auditedTypeUuids, $request) {
            $query->where(function ($q) use ($request) {
                // 用户自己申请的记录
                $q->where('r.wxappUserUuid', '=', $request->uuid);
            })
                ->whereOr(function ($q) use ($auditedTypeUuids) {
                    // 用户有审核权限的记录
                    if (!empty($auditedTypeUuids)) {
                        $q->whereIn('r.typeUuid', $auditedTypeUuids);
                    }
                });
        });

        //状态,待审核-0,审核通过-1，已过期-2
        if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
            if ($data['status'] == 2) {
                array_push($searchWhere, ['r.expiredTime', '<', date('Y-m-d H:i:s')]);
            } else {
                array_push($searchWhere, ['r.status', '=', $data['status']]);
                array_push($searchWhere, ['r.expiredTime', '>', date('Y-m-d H:i:s')]);
            }
        }
        if (!empty($data['name'])) array_push($searchWhere, ['rt.name|rt.subtitle|r.subcontractor|w.workerName', 'like', "%" . $data['name'] . "%"]);
        $list =  DB::table('certificate_risk')
            ->alias('r')
            ->leftjoin('certificate_riskType rt', 'r.typeUuid = rt.uuid')
            ->join('certification_projectWorker w', 'w.wxappUserUuid = r.wxappUserUuid', 'left')
            ->where($searchWhere)
            ->order(['r.id desc'])
            ->page((int)$page, (int)$limit)
            ->field(['rt.name as typeName', 'r.inDate', 'r.status', 'r.uuid', 'r.expiredTime', 'r.subcontractor', 'r.location', 'rt.subtitle'])
            ->distinct(true)
            ->select()->toArray();
        foreach ($list as &$item) {
            if (strtotime($item['expiredTime']) < time()) {
                $item['status'] = '2'; //已过期
            }
        }
        //是否有申请权限
        $result['hasAuth'] = DB::table('certificate_areaWorker')->alias('a')
            ->join('certificate_riskTypeAuth ta', 'ta.wxappUserUuid = a.wxappUserUuid')
            ->where('ta.wxappUserUuid', $request->uuid)
            ->where('a.isDelete', 0)
            ->where('ta.isDelete', 0)->find() ? 1 : 0;
        $result['list'] = $list;

        return result(SUCCESS, $result, '');
    }

    /**
     * @Description: 许可证申请
     * @param {Request} $request
     */
    public function apply(Request $request)
    {
        $data  = $request->data;
        $wxappUserUuid = $request->uuid;

        $typeUuid = $data['typeUuid'];
        $formData = html_entity_decode($data['formData']);
        $type = DB::table('certificate_riskType')->where(['isDelete' => 0, 'uuid' => $typeUuid])->find();
        if (!$type)  return result(FAIL, '', '许可证类型已被删除或错误！');

        //是否有申请权限
        $auth = DB::table('certificate_areaWorker')->alias('a')
            ->join('certificate_areaType t', 't.areaUuid=a.areaUuid')
            ->join('certificate_area ar', 'ar.uuid=a.areaUuid')
            ->join('certificate_riskTypeAuth ta', 'ta.wxappUserUuid=a.wxappUserUuid')
            ->where('ta.typeUuid', $typeUuid)
            ->where('ar.uuid', $data['areaUuid'])
            ->where('a.isDelete', 0)
            ->where('ta.isDelete', 0)
            ->where('a.wxappUserUuid', $request->uuid)->find();
        if (empty($auth)) return result(FAIL, '', '您没有申请权限');

        DB::startTrans();
        try {
            $auditUser =  DB::table('certificate_riskTypeAuth')
                ->alias('rta')
                ->join('certificate_areaType at', 'at.areaUuid=rta.typeUuid')
                ->where('at.areaUuid', $data['areaUuid'])
                ->where('rta.typeUuid', $typeUuid)
                ->where('rta.isAudit', 1)
                ->find();
            $riskData = [
                'typeUuid'      => $typeUuid,
                'wxappUserUuid' => $wxappUserUuid,
                'status'        => 0,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'areaUuid'      => $data['areaUuid'],
                'auditUserUuid' => $auditUser['wxappUserUuid'] ?? '',
                'expiredTime'   => $data['expiredTime'] . ' 23:59:59',
                'subcontractor' => $data['subcontractor'] ?? '',
                'location'      => $data['location'] ?? ''
            ];
            DB::table('certificate_risk')->insert($riskData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $riskData['uuid']], '提交成功，请等待项目管理员审核');
        } catch (\Exception $e) {
            dump($e->getMessage());
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    /**
     * 获取详情
     *
     * @param Request $request
     * @return void
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $where = [
            'r.isDelete' => 0,
            'r.uuid' => $uuid
        ];
        //查看有没有提交过的记录
        $riskData = DB::table('certificate_risk')
            ->alias('r')
            ->join('certificate_area a', 'a.uuid=r.areaUuid')
            ->where($where)
            ->order('r.id DESC')
            ->field(['r.formData', 'r.expiredTime', 'r.status', 'r.uuid', 'r.typeUuid', 'r.subcontractor', 'r.location', 'r.areaUuid', 'a.name as areaName'])
            ->findOrEmpty();
        if (!$riskData) return result(FAIL, '', '獲取失敗，請返回重試');

        //是否有申请权限
        $auth = DB::table('certificate_areaWorker')->alias('a')
            ->join('certificate_areaType t', 't.areaUuid=a.areaUuid')
            ->join('certificate_area ar', 'ar.uuid=a.areaUuid')
            ->join('certificate_riskTypeAuth ta', 'ta.wxappUserUuid=a.wxappUserUuid')
            ->where('ta.typeUuid', $riskData['typeUuid'])
            ->where('a.isDelete', 0)
            ->where('ta.isDelete', 0)
            ->where('a.wxappUserUuid', $request->uuid)->find();
        if (empty($auth)) return result(FAIL, '', '您没有权限查看');

        //判断当前用户权限，是否是区域管理员
        $riskTypeAuth = DB::table('certificate_riskTypeAuth')->where('wxappUserUuid', $request->uuid)->where('typeUuid', $riskData['typeUuid'])->find();
        $riskData['isAudit'] = $riskTypeAuth['isAudit'] ?? 0;

        $riskData['formData'] = json_decode(html_entity_decode($riskData['formData']), true);
        $riskData['signFormTemplate'] = [];
        if ($riskData['isAudit'] != 1) {
            foreach ($riskData['formData'] as $key => $value) {
                if ($value['tag'] == 'signature') {
                    unset($riskData['formData'][$key]);
                }
            }
        }
        $formTemplate = DB::table('certificate_riskType')
            ->alias('rt')
            ->join('certificate_formtemplate f', 'f.uuid=rt.formUuid', 'left')
            ->where('rt.uuid', $riskData['typeUuid'])
            ->value('f.fields');
        $formTemplate = json_decode(html_entity_decode($formTemplate), true) ?? [];
        foreach ($formTemplate as $key => $value) {
            if ($value['tag'] == 'signature') {
                $riskData['signFormTemplate'][] = $value;
            }
        }

        //是否已审核签名
        $riskData['isSigned'] = $riskData['status'] == 1 ? 1 : 0;
        if (strtotime($riskData['expiredTime']) < time()) {
            $riskData['status'] = '2'; //已过期
        }
        return result(SUCCESS, $riskData, '');
    }

    /**
     * @Description: 许可证审核
     * @param {Request} $request
     */
    public function audit(Request $request)
    {
        $data  = $request->data;
        $userUuid = $request->uuid;
        $formData = html_entity_decode($data['formData']);
        DB::startTrans();
        try {
            $where = [
                'isDelete' => 0,
                'uuid' => $data['uuid'],
            ];
            $riskData = DB::table('certificate_risk')->where($where)->find();
            if (!$riskData) {
                return result(FAIL, '', '申请记录不存在');
            }
            if ($riskData['status'] != 0) {
                return result(FAIL, '', '该记录已审批');
            }

            $auth = DB::table('certificate_riskTypeAuth')->alias('rt')
                ->join('certificate_areaWorker a', 'rt.wxappUserUuid = a.wxappUserUuid')
                ->where('rt.wxappUserUuid', $request->uuid)
                ->where('rt.typeUuid', $riskData['typeUuid'])
                ->where('rt.isAudit', 1)
                ->where('a.isDelete', 0)
                ->where('rt.isDelete', 0)->find();
            if (!$auth)  return result(FAIL, '', '没有审批权限');

            $formData2 = json_decode(html_entity_decode($formData), true) ?? [];
            $isSigned = 0;
            //必须要有签名字段
            foreach ($formData2 as $key => $value) {
                if ($value['tag'] == 'signature') {
                    $isSigned = 1;
                }
            }
            if ($isSigned == 0)  return result(FAIL, '', '缺少签名字段');

            $updateData['formData']      = $formData;
            $updateData['status']        = $data['status'];
            $updateData['auditUserUuid'] = $userUuid;
            $updateData['auditTime']     = date('Y-m-d H:i:s');
            DB::table('certificate_risk')->where($where)->update($updateData);
            DB::commit();
            return result(SUCCESS, '', '审核成功');
        } catch (\Exception $e) {
            DB::rollback();
        }
        return result(FAIL, '', '审核失败,请重试');
    }
}
